package com.realshare.frame.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

public class StringUtils {


    /**
     * 2进制数字转换为16进制字符串
     *
     * @param data
     * @return
     */
    public static String parseByteArray2HexStr(byte[] data) {
        if (data == null || data.length < 1) {
            return null;
        }

        StringBuilder hex = new StringBuilder();
        for (byte aData : data) {
            int h = aData & 0XFF;
            if (h < 16) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(h));
        }

        return hex.toString();
    }

    /**
     * 16进制字符串转换为2进制数字
     *
     * @param hex
     * @return
     */
    public static byte[] parseHexStr2ByteArray(String hex) {
        if (hex == null || "".equals(hex)) {
            return null;
        }

        int length = hex.length() >> 1;
        byte[] data = new byte[length];
        for (int i = 0; i < length; i++) {
            int n = i << 1;
            int height = Integer.valueOf(hex.substring(n, n + 1), 16);
            int low = Integer.valueOf(hex.substring(n + 1, n + 2), 16);
            data[i] = (byte) (height * 16 + low);
        }

        return data;
    }

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        return (str == null) || (str.length() < 1);
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    /**
     * 判断字符串是否为纯数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 转换成Unicode编码
     *
     * @param str  要转换的字符串
     * @param type 格式，0 &#x;格式 ,1 \\u格式，2简化格式
     * @return
     */
    public static String toUnicode(String str, int type) {
        StringBuffer uString = new StringBuffer();
        String CharStr = "";
        for (int i = 0; i < str.length(); i++) {
            CharStr = Integer.toHexString(str.charAt(i));
            if (CharStr.length() > 3) {
                switch (type) {
                    case 0:
                        uString.append("&#x" + CharStr + ";");
                        break;
                    case 1:
                        uString.append("\\u" + CharStr);
                        break;
                    case 2:
                        uString.append("~" + CharStr);
                        break;
                }

            } else {
                uString.append(str.charAt(i));
            }
        }
        return uString.toString();
    }

    /**
     * 字符串替换
     *
     * @param Str
     * @param a
     * @param b
     * @return
     */
    public static String replace(String Str, String a, String b) {
        if (a.equals(b)) {
            return Str;
        }
        if ((Str == null) || (Str.equals(""))) {
            return "";
        }
        if ((a == null) || (a.equals(""))) {
            return Str;
        }
        if (b == null) {
            b = "";
        }
        String dst = Str;
        int idx = dst.indexOf(a);

        while (idx >= 0) {
            dst = dst.substring(0, idx) + b + dst.substring(idx + a.length(), dst.length());
            idx = dst.indexOf(a, idx + b.length());
        }
        return dst;
    }

    /**
     * 格式化日期
     *
     * @param dStr
     * @param dType
     * @return
     */
    public static String formatDate(String dStr, String dType) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d = sd.parse(dStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);
            dType = replace(dType, "yyyy", String.valueOf(calendar.get(1)));
            dType = replace(dType, "MM", String.valueOf(calendar.get(2) + 1));
            dType = replace(dType, "dd", String.valueOf(calendar.get(5)));
            dType = replace(dType, "HH", String.valueOf(calendar.get(11)));
            dType = replace(dType, "mm", String.valueOf(calendar.get(12)));
            dType = replace(dType, "ss", String.valueOf(calendar.get(13)));
            return dType;
        } catch (ParseException e) {
        }
        return "";
    }

    public static String jsEncoder(String src) {
        if (src == null) {
            return "";
        }
        String dst = src;
        dst = replace(dst, "'", "\\'");
        dst = replace(dst, "\"", "\\\"");
        dst = replace(dst, "\n", "\\\n");
        dst = replace(dst, "\r", "\\\n");
        return dst;
    }

    /**
     * 转换成HTML格式输出
     *
     * @param Text
     * @return
     */
    public static String htmlEncoder(String Text) {
        String dst = Text;
        dst = replace(dst, "<", "&lt;");
        dst = replace(dst, ">", "&rt;");
        dst = replace(dst, "\"", "&quot;");
        dst = replace(dst, "'", "&acute;");

        dst = replace(dst, " ", "&nbsp;");
        dst = replace(dst, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        dst = replace(dst, "\r\n", "<br />");
        dst = replace(dst, "\r", "<br />");
        dst = replace(dst, "\n", "<br />");
        return dst;
    }

    /**
     * HTML转换成文本
     *
     * @param Html
     * @return
     */
    public static String html2Text(String Html) {
        Html = Html.replaceAll("<style .+?>.+?</style>", "");
        Html = Html.replaceAll("<script .+?>.+?</script>", "");
        Html = Html.replaceAll("<.+?>", "");
        Html = Html.replaceAll("&nbsp;", " ");
        return Html;
    }

    /**
     * 截取中文字符串,(汉字按两个长度算，英文按一个长度)
     *
     * @param Str 原字符串
     * @param Len 要截取的长度
     * @return
     */
    public static String leftZH(String Str, int Len) {
        if (Len < 1) {
            return Str;
        }
        if (isBlank(Str)) {
            return "";
        }
        byte[] btStr = Str.getBytes();
        int StrLen = btStr.length;
        if (StrLen <= Len) {
            return Str;
        }
        Len -= 2;
        int Left = 0;
        int LeftLen = 0;
        for (int i = 0; i < StrLen; i++) {
            if (btStr[i] > 0) {
                if (Left + 1 > Len) {
                    break;
                }
                Left++;
            } else {
                if (Left + 2 > Len) {
                    break;
                }
                Left += 2;
                i++;
            }
            LeftLen++;
        }
        return Str.substring(0, LeftLen) + "…";
    }

    public static String leftZH_CN(String Str, int Len) {
        return StringUtils.leftZH(Str, Len);
    }

    /**
     * 获取汉字的拼音
     *
     * @param chString 汉字字符串
     * @param style    拼音格式:全拼带声调，全拼不带声调，拼音首字母
     * @return
     */
    public static ArrayList<String> getPinyinString(String chString, int style) {
        HanyuPinyinOutputFormat pyformat = new HanyuPinyinOutputFormat();
        pyformat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        if (style == 0) {
            pyformat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        }
        pyformat.setVCharType(HanyuPinyinVCharType.WITH_V);
        ArrayList<String[]> pinyinList = new ArrayList<String[]>();
        String[] pinyin = (String[]) null;
        for (int i = 0; i < chString.length(); i++) {
            if (String.valueOf(chString.charAt(i)).getBytes()[0] >= 0) {
                pinyin = new String[1];
                pinyin[0] = String.valueOf(chString.charAt(i));
            } else {
                try {
                    pinyin = PinyinHelper.toHanyuPinyinStringArray(chString.charAt(i), pyformat);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    pinyin = new String[1];
                    pinyin[0] = String.valueOf(chString.charAt(i));
                }
                if (pinyin == null) {
                    pinyin = new String[1];
                    pinyin[0] = String.valueOf(chString.charAt(i));
                }
            }
            if (style == 2) {
                for (int j = 0; j < pinyin.length; j++) {
                    pinyin[j] = String.valueOf(pinyin[j].charAt(0));
                }
            }
            pinyinList.add(pinyin);
            pinyin = (String[]) null;
        }
        ArrayList<String> loc = new ArrayList<String>();
        ArrayList<String> loc2 = new ArrayList<String>();
        int pinyinLength = pinyinList.size();

        for (int i = 0; i < pinyinLength; i++) {
            for (int j = 0; j < ((String[]) pinyinList.get(i)).length; j++) {
                if (i == 0) {
                    loc2.add(((String[]) pinyinList.get(i))[j]);
                } else {
                    for (int k = 0; k < loc.size(); k++) {
                        loc2.add((String) loc.get(k) + ((String[]) pinyinList.get(i))[j]);
                    }
                }
            }
            loc.clear();
            loc.addAll(loc2);
            loc2.clear();
        }
        for (int i = 0; i < loc.size(); i++) {
            if (loc2.contains(loc.get(i))) {
                continue;
            }
            loc2.add((String) loc.get(i));
        }

        return loc2;
    }

    /**
     * 将long型的文件大小转换成字符串形式
     *
     * @param FileSize
     * @return
     */
    public static String getFileSize(long FileSize) {
        String SizeStr = "";
        String SizeName = " bytes";
        double size = FileSize;
        if (FileSize > 1000L) {
            size = FileSize / 1024.0D;
            SizeName = " KB";
            if (size > 1000.0D) {
                size = FileSize / 1048576.0D;
                SizeName = " MB";
                if (size > 1000.0D) {
                    size = FileSize / 1073741824.0D;
                    SizeName = " GB";
                }
            }
        }
        size = Math.round(size * 100.0D) / 100.0D;
        SizeStr = size + SizeName;
        return SizeStr;
    }

}
